package com.zifan.sever.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zifan.sever.config.security.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * OncePerRequestFilter这个是boot内置的拦截器
 * jwt登录授权过滤器
 * @author Zifan
 * @date 2021年04月10日18:12
 */
public class JwtTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authHeader = request.getHeader(tokenHeader);
        //存在token,并且token是以tokenHeader（Bearer，）开头
        if (StrUtil.isNotEmpty(authHeader) && authHeader.startsWith(tokenHead)){
            //字符串截取
            String authToken = authHeader.substring(tokenHead.length());
            //根据token去拿到用户名
            String name = jwtTokenUtils.getUserNameFromToken(authToken);
            //没有登录 token存在用户名，但未登录
            if (StrUtil.isNotEmpty(name) && ObjectUtil.isNull(SecurityContextHolder.getContext().getAuthentication()) ){
                //登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(name);
                //验证token是否有效，重新设置用户对象
                if (jwtTokenUtils.validateToken(authToken,userDetails)){
                    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

                }
            }
        }
        //放行
        filterChain.doFilter(request,response);
    }
}
